package org.idea.qiyu.framework.utils.queue;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author linhao
 * @Date created in 4:26 下午 2022/1/12
 */
public class BlockQueue {

    private Object[] arr = new Object[100];

    private Integer size = 0;

//    private static boolean addBlockFlag = false;

//    private static boolean takeBlockFlag = true;

    private ReentrantLock reentrantLock  = new ReentrantLock();

    private Condition condition = reentrantLock.newCondition();

    private Condition addCondition = reentrantLock.newCondition();

    private static Object stat = new Object();

    public void addItem(Object item) {
       synchronized (stat){
           arr[size] = item;
           size++;
           System.out.print(1);
       }
    }

    public Object take() {
        synchronized (stat){
            if (size == 0) {
                return null;
            }
            Object result = arr[size - 1];
            size--;
            System.out.print(0);
            return result;
        }
    }

    public void display() {
        for (Object item : arr) {
            if (item != null) {
                System.out.println(item);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        BlockQueue blockQueue = new BlockQueue();
        Thread provider = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    blockQueue.addItem("item" + UUID.randomUUID().toString());
                }
            }
        });
        provider.start();
        Thread.sleep(1000);
        Thread consumer = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int j=0;j<100;j++){
                    Object r = blockQueue.take();
//                    try {
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                }
            }
        });
        consumer.start();
        countDownLatch.await();
    }
}
